package com.example.nftapp.frg.market;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.nftapp.R;
import com.example.nftapp.adapter.MarketPagerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MarketFragment extends Fragment {

    // 声明组件
    TabLayout tabMarket;
    ViewPager2 vpMarket;
    MarketPagerAdapter adapter;

    // 存放内部嵌套的横向滑动的Fragment
    List<Fragment> fragments = new ArrayList<>();
    // 存放TabLayout标签名称
    List<String> tabs = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_market, container, false);
        // 初始化组件
        tabMarket = view.findViewById(R.id.tabsMarket);
        vpMarket = view.findViewById(R.id.vpMarket);

        // 准备数据
        fragments.add(new MarketFragment_PX());
        fragments.add(new MarketFragment_QB());
        fragments.add(new MarketFragment_DT());

        tabs.add("排序");
        tabs.add("全部分类");
        tabs.add("动态");

        adapter = new MarketPagerAdapter(requireActivity(), fragments);
        vpMarket.setAdapter(adapter);
        new TabLayoutMediator(tabMarket, vpMarket, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                View customView = LayoutInflater.from(requireActivity()).inflate(R.layout.layout_custom_tab_market, null);
                TextView tvTitle = customView.findViewById(R.id.tv_title);
                ImageView ivLeft = customView.findViewById(R.id.iv_left_icon);
                tvTitle.setText(tabs.get(position));
                switch (position) {
                    case 0:
                        ivLeft.setImageResource(R.mipmap.ic_px);
                        break;
                    case 1:
                        ivLeft.setImageResource(R.mipmap.ic_qb);
                        break;
                    case 2:
                        ivLeft.setImageResource(R.mipmap.ic_dt);
                        break;
                }
                tab.setCustomView(customView);
            }
        }).attach();
        Objects.requireNonNull(tabMarket.getTabAt(1)).select();
        return view;
    }

}